<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\shop\Article;
use app\admin\model\shop\Likelog;
use app\admin\model\shop\Order as OrderList;
use app\admin\model\shop\Shoplist;
use app\common\controller\Api;
use think\Config;
use Yansongda\Pay\Exceptions\Exception;
use EasyWeChat\Payment\Order;

/**
 * 商品接口
 */
class Shop extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];//['test', 'test1'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];//['test2'];

    /**
     * 添加文章
     *
     * @ApiTitle    (添加文章)
     * @ApiSummary  (添加文章)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/shop/addArticle)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="user_id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="shoplist_id", type="string", required=true, description="商品ID")
     * @ApiParams   (name="title", type="string", required=true, description="标题")
     * @ApiParams   (name="content", type="string", required=true, description="内容")
     * @ApiParams   (name="smallimages", type="string", required=true, description="图片 demo xx1.jpg,xx2.jpg")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="string", required=true, sample="{}")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function addArticle()
    {
        $data=[];
        $data['user_id'] = $this->request->request("user_id/d");
        $data['shoplist_id'] = $this->request->request("shoplist_id/d");
        $data['title'] = $this->request->request("title/s");
        $data['content'] = $this->request->request("content/s");
        $data['smallimages'] = $this->request->request("smallimages/s");
        if (!$data['user_id']  || !$data['content'] || !$data['smallimages']){
            return $this->error('提交内容不合法!');
        }
        if (!$data['shoplist_id']){
            $data['shoplist_id'] = 0;
        }
        $data['status'] = Config::get("site.article_type");
        Article::create($data);
        Shoplist::where('id','=',$data['shoplist_id'])->setInc('recommend');
        $this->success('返回成功', $this->request->param());
    }



    /**
     * 创建订单
     *
     * @ApiTitle    (创建订单)
     * @ApiSummary  (创建订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/shop/createOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="shoplist_id", type="int", required=true, description="商品ID")
     * @ApiParams   (name="order_id", type="int", required=true, description="发起拼单的ID")
     * @ApiParams   (name="type", type="string", required=true, description="支付方式 alipay wechat")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="string", required=true, sample="{}")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    //ALTER TABLE `fa_shoplist` CHANGE `manystore_id` `shop_id` INT(11) NOT NULL COMMENT '商家ID';
    //ALTER TABLE `fa_setmeal` CHANGE `manystore_id` `shop_id` INT(11) NOT NULL COMMENT '商家id';
    public function createOrder(){
        $token = $this->auth->getUserinfo();
        $shoplist_id = $this->request->request("shoplist_id/d");
        $order_id = $this->request->request("order_id/d",'');
        $type = $this->request->request("type/s");
        if  ($type != 'wechat' && $type != 'alipay')  return  $this->error('支付方式不正确!');
        $shop = Shoplist::where('id','=',$shoplist_id)->find();

        if ($order_id){
            $order = OrderList::where('id','=',$order_id)->find();
            if (!$order) return  $this->error('拼单不存在');
            if ($order['spell_status'] == 1) return  $this->error('拼单已完成');
            if ($order['spell_num'] <= $order['join_spell_num'])  return  $this->error('拼单已满员');
            if ($order['user_id'] == $token['user_id']) return  $this->error('不可以和自己拼单');
        }
        //订单表
        $data['order_sn'] = createNumber();
        $data['user_id'] = $token['user_id'];
        $data['shoplist_id'] = $shoplist_id;
        $data['status'] = 0;
        $data['type'] = $type;
        if ($shop['spell_status'] == 0){
            $data['spell_num'] = 1;
            $data['join_spell_num'] = 1;
            $data['spell_status'] = 1;
        }else{
            $data['spell_num'] = $shop['spell_num'];
            $data['join_spell_num'] = 0;
            $data['spell_status'] = 0;
        }
        if ($order_id){
            $data['order_id'] = $order_id;//拼单存在
        }else{
            $data['order_id']=0;
        }
        $data['paytimestamp'] = 0;
        $data['actualpayment'] = $shop['price'];
        $data['ordertype'] = 0;
        $shopadd = OrderList::create($data);
        //存在拼单
        if ($shopadd && isset($order)) {
            $order->join_spell_num = $order->join_spell_num+1;//拼单存在
            if ($order->spell_num == $order->join_spell_num) {
                $order->spell_status = 1;
                OrderList::where('order_id', '=', $order_id)->update(['spell_status' => 1]);
            }
            $order->save();//拼单完成
        }
        return $this->success('下单成功',$shopadd);

    }


    /**
     * 付款
     *
     * @ApiTitle    (付款)
     * @ApiSummary  (付款)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/shop/payOrder)
     * @ApiParams  (name=ordersn, type=string, required=true, description="订单号")
     * @ApiParams   (name="type", type="string", required=true, description="支付方式 alipay wechat")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="string", required=true, sample="{}")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function payOrder(){
        $token = $this->auth->getUserinfo();
        $out_trade_no = $this->request->request("ordersn");
        $type = $this->request->request("type");
        $order = OrderList::where('order_sn','=',$out_trade_no)->where('user_id','=',$token['user_id'])->find();
        if (!$order) return $this->error('订单不存在');
        if ($order['status'] != 0) return $this->error('订单已完成,无法支付');
        $method = 'web';
        if ($type == 'wechat') {
            $isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
            if ($isWechat){
                $method = 'mp';
            }else{
                $method = 'wap';
            }
        }

        //订单标题
        $title = config('site.name').'-订单支付';
        $amount = $order['actualpayment'];//$this->request->request('amount'); //实际下单价格

        //回调链接
        //$notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $notifyurl = $this->request->root(true) . '/api/shop/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
        try {
            $data = [];
            $data['method'] = $method;
            $data['type'] = $type;
            $pay = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);
            if ($method == 'wap') {
                $url = request()->domain() . '/api/jump/jump?url=' . base64_encode($pay);
                $data['data'] = $url;
            }else{
                $data['data'] = $pay;
            }
//            return  Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);
            return  $this->success('成功',$data);
        } catch (Exception $e) {
            return $this->error($e);
        }

    }


    /**
     * 支付成功
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $order = \app\admin\model\shop\Order::where('ordersn','=',$out_trade_no)->where('status','=',0)->find();
            if ($order){
                $order->status =1;
                $order->paytimestamp =time();
                $order->verificationcode = mt_rand(100000,999999);
                $order->save();
            }
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
        }
        echo $pay->success();
    }






    /**
     * 点赞
     *
     * @ApiTitle    (点赞)
     * @ApiSummary  (点赞)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/shop/setLike)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="user_id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="id", type="string", required=true, description="商品ID")
     * @ApiParams   (name="type", type="string", required=true, description="1是商品 2是评论")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="string", required=true, sample="{}")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function setLike()
    {
        $user_id = $this->request->request("user_id/d");
        $id = $this->request->request("id/d");
        $type = $this->request->request("type/d");


        if (Likelog::where('user_id', $user_id)->where('type', $type)->where('reqid', $id)->find()) {
            return $this->error('已经点赞过了');
        }
        if ($type == 1) {
            Shoplist::where('id', '=', $id)->setInc('shoplike');
        } elseif ($type == 2) {
            Article::where('shoplist_id', '=', $id)->setInc('likenum');
        }
        Likelog::create([
            'user_id'=>$user_id,
            'type'=>$type,
            'reqid'=>$id,


        ]);
       return $this->success('点赞完成');
    }

//    /**
//     * 无需登录的接口
//     *
//     */
//    public function test1()
//    {
//        $this->success('返回成功', ['action' => 'test1']);
//    }
//
//    /**
//     * 需要登录的接口
//     *
//     */
//    public function test2()
//    {
//        $this->success('返回成功', ['action' => 'test2']);
//    }
//
//    /**
//     * 需要登录且需要验证有相应组的权限
//     *
//     */
//    public function test3()
//    {
//        $this->success('返回成功', ['action' => 'test3']);
//    }

}
